package top.wardyan.wtask.jobs;
import java.sql.Timestamp;
import java.util.concurrent.ExecutorService;

import com.jfinal.aop.Aop;
import com.jfinal.kit.Prop;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.event.EventDispatcher;
import com.lark.oapi.service.im.ImService;
import com.lark.oapi.service.im.v1.model.P2MessageReceiveV1;
import com.lark.oapi.ws.Client;

import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ExecutorBuilder;
import cn.hutool.core.thread.ThreadUtil;
import top.wardyan.base.common.config.ConfigProp;
import top.wardyan.base.common.util.DateUtil;
import top.wardyan.wtask.feishu.api.FeishuMsgBusiness;

public class FeishuSubscribe {
  	// onP2MessageReceiveV1 为接收消息 v2.0；onCustomizedEvent 内的 message 为接收消息 v1.0。
	
	private static final Prop PROP = ConfigProp.load();
	private static final String APPID = PROP.get("feishu.app_id");
	private static final String SECRET = PROP.get("feishu.app_secret");
	private static final String CONTAINERID = PROP.get("feishu.container_id");
	private static final Integer PAGESIZE = PROP.getInt("feishu.pagesize", 50);
	private static final String USERINFO_URL = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/";
	
	
	private static final ExecutorService executor = ExecutorBuilder.create()//
			.setCorePoolSize(1)//
			.setMaxPoolSize(10)//
			.setKeepAliveTime(600)//
			.build();

	
	private static final Runnable task = new Runnable() {

		@Override
		public void run() {
			Console.log(DateUtil.formatNow(), "收到消息通知,等待1秒后再行读取");
        	// 停一分钟再拉取
        	ThreadUtil.sleep(1000);
        	FeishuMsgBusiness feishuMsgBusiness = Aop.get(FeishuMsgBusiness.class);
        	Timestamp date = DateUtil.range(19);	// 从昨天开始
        	feishuMsgBusiness.spy(date, false, "");
		}
		
	};
	
    private static final EventDispatcher EVENT_HANDLER = EventDispatcher.newBuilder("", "")
            .onP2MessageReceiveV1(new ImService.P2MessageReceiveV1Handler() {
                @Override
                public void handle(P2MessageReceiveV1 event) throws Exception {
                	//System.out.printf("[ onP2MessageReceiveV1 access ], data: %s\n", Jsons.DEFAULT.toJson(event.getEvent()));
                	executor.execute(task);
                }
            })
            // .onCustomizedEvent("这里填入你要自定义订阅的 event 的 key，例如 out_approval", new CustomEventHandler() {
//            .onCustomizedEvent("im.message.receive_v1", new CustomEventHandler() {
//                @Override
//                public void handle(EventReq event) throws Exception {
//                    System.out.printf("[ onCustomizedEvent access ], type: message, data: %s\n", new String(event.getBody(), StandardCharsets.UTF_8));
//                }
//            })
            .build();

    
    public static void main(String[] args) {
        Client cli = new Client.Builder(APPID, SECRET)
                .eventHandler(EVENT_HANDLER)
                .build();
        cli.start();
    }
    
    public static void start() {
    	
    	ThreadUtil.execute(new Runnable() {

			@Override
			public void run() {

		        Client cli = new Client.Builder(APPID, SECRET)
		                .eventHandler(EVENT_HANDLER)
		                .build();
		        cli.start();
			}
    		
    	});
    	Console.log("飞书消息订阅完成...");
    }
}